package com.iweb.user.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.iweb.commons.token.JwtUtil;
import com.iweb.user.model.User;
import com.iweb.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jack
 * @since 2020-05-10
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping
    public ResponseEntity<User> addUser(@RequestBody User user) {

        // 密码加密
        String md5Hex = DigestUtil.md5Hex(user.getPassword());
        log.info("加密后的数据密码:{}", md5Hex);
        user.setPassword(md5Hex);
        // 注册用户
        userService.save(user);
        // 返回结果
        return ResponseEntity.ok(user);
    }

    @PostMapping("login")
    public ResponseEntity login(@RequestBody User user) {
        // 密码加密
        String md5Hex = DigestUtil.md5Hex(user.getPassword());
        log.info("加密后的数据密码:{}", md5Hex);
        user.setPassword(md5Hex);
        User userData = userService.getOne(new QueryWrapper<>(user));
        if (ObjectUtil.isEmpty(userData)) {
            return ResponseEntity.ok("用户名或密码错误");
        } else {
            // 登录成功
            Map<String, String> info = new HashMap<>();
            info.put("username", user.getAccount());
            // 生成token
            String token = JwtUtil.createJWT(UUID.randomUUID().toString(), user.getAccount(), null);
            info.put("token", token);
            return ResponseEntity.ok(info);
        }
    }

}

